function Promise(excutor) {
    this.PromiseState = 'pendding';
    this.PromiseResult = undefined;
    this.callBack = [];
    // [
    //     {
    //         ok:fn,
    //         err:fn
    //     },
    //     {
    //         ok:fn, 
    //         err:fn
    //     }
    // ]
    let res = (val) => {

        if( this.PromiseState !== 'pendding')return;
        // 执行函数
        // console.log(val);
        this.PromiseState = 'fulfilled';
        this.PromiseResult = val;

        // 执行异步then 回调函数 方法
        this.callBack.forEach(item => {
            item.ok(val)
        })

    }

    let rej = (rea) => {
        if( this.PromiseState !== 'pendding')return;

        this.PromiseState = 'rejected';
        this.PromiseResult = rea;

        this.callBack.forEach(item => {
            item.err(rea)
        })
    }

    try {
        excutor(res, rej)
    } catch (err) {
        rej(err)
    }
}

Promise.prototype.then = function (onResolve, onReject) {
    return new Promise((res, rej) => {

        let handle = (fnName) => {
            try {
                let result = fnName(this.PromiseResult);
                if (result instanceof Promise) {
                    result.then(val => {
                        res(val)
                    }, rea => {
                        rej(rea)
                    })
                } else {
                    res(result)
                }
            } catch (err) {
                rej(err)
            }
        }

        if (this.PromiseState === 'fulfilled') {
            handle(onResolve)
        }

        if (this.PromiseState === 'rejected') {
            handle(onReject)
        }

        // 异步
        if (this.PromiseState === 'pendding') {
            this.callBack.push({
                ok: () => {
                    handle(onResolve)
                },
                err: () => {
                    handle(onReject)
                }
            })
        }
    })

}
